<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <el-tabs v-model="activeTab" class="demo-tabs">
          <el-tab-pane label="登录" name="login"></el-tab-pane>
          <el-tab-pane label="注册" name="register"></el-tab-pane>
        </el-tabs>
      </template>

      <!-- 登录表单 -->
      <el-form 
        v-if="activeTab === 'login'"
        :model="loginForm" 
        :rules="loginRules"
        ref="loginFormRef"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="验证码答案"
              class="captcha-input"
            />
            <div 
              v-if="captchaType === 'math'" 
              class="math-captcha"
              @click="refreshCaptcha"
            >
              <span>{{ captchaExpression }}</span>
              <div class="math-tip">点击刷新</div>
            </div>
            <img
              v-else
              :src="captchaImage"
              class="captcha-image"
              @click="refreshCaptcha"
              alt="点击刷新验证码"
            />
          </div>
        </el-form-item>
        
        <el-form-item>
          <div class="captcha-controls">
            <el-radio-group v-model="captchaTypePreference" @change="refreshCaptcha">
              <el-radio label="math">数学计算</el-radio>
              <el-radio label="image">图片验证码</el-radio>
            </el-radio-group>
            <el-button 
              type="text" 
              @click="refreshCaptcha" 
              icon="RefreshRight"
            >
              刷新验证码
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleLogin" 
            :loading="loading"
            class="submit-button"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form 
        v-else
        :model="registerForm" 
        :rules="registerRules"
        ref="registerFormRef"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="用户名"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="确认密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleRegister" 
            :loading="loading"
            class="submit-button"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import { login, register, getCaptcha } from '../api/auth'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const activeTab = ref('login')
const captchaImage = ref('')
const captchaId = ref('')
const captchaType = ref('math')
const captchaExpression = ref('')
const captchaTypePreference = ref('math')

// 登录相关
const loginFormRef = ref(null)
const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 注册相关
const registerFormRef = ref(null)
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: 'blur' }
  ]
}

const refreshCaptcha = async () => {
  try {
    const { data } = await getCaptcha(captchaTypePreference.value)
    captchaId.value = data.captchaId
    captchaType.value = data.type
    
    // 清空之前的验证码输入
    loginForm.captcha = ''
    
    if (data.type === 'math') {
      captchaExpression.value = data.expression
      captchaImage.value = ''
    } else {
      captchaImage.value = data.image
      captchaExpression.value = ''
    }
  } catch (error) {
    ElMessage.error('获取验证码失败，请刷新重试')
    console.error('获取验证码失败:', error)
    // 3秒后自动重试
    setTimeout(refreshCaptcha, 3000)
  }
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const userRole = await userStore.login({
          username: loginForm.username,
          password: loginForm.password,
          captchaId: captchaId.value,
          captcha: loginForm.captcha
        })
        ElMessage.success('登录成功')
        
        // 根据用户角色跳转到不同页面
        if (userRole === 'ROLE_ADMIN') {
          router.push('/admin')
        } else {
          router.push('/translator')
        }
      } catch (error) {
        // 显示更具体的错误信息
        if (error.message.includes('验证码')) {
          ElMessage.error('验证码错误，请重新输入')
        } else if (error.message.includes('用户不存在')) {
          ElMessage.error('用户不存在，请先注册')
        } else if (error.message.includes('密码错误')) {
          ElMessage.error('密码错误，请重新输入')
        } else {
          ElMessage.error(error.message || '登录失败')
        }
        refreshCaptcha()
      } finally {
        loading.value = false
      }
    }
  })
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await register({
          username: registerForm.username,
          password: registerForm.password
        })
        ElMessage.success('注册成功，请登录')
        activeTab.value = 'login'
        loginForm.username = registerForm.username
        loginForm.password = ''
        refreshCaptcha()
      } catch (error) {
        // 显示更具体的错误信息
        if (error.message.includes('已存在')) {
          ElMessage.error('用户名已存在，请更换其他用户名')
        } else if (error.message.includes('密码')) {
          ElMessage.error('密码格式不正确，请检查后重试')
        } else {
          ElMessage.error(error.message || '注册失败')
        }
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f6fa;
}

.login-card {
  width: 400px;
}

.submit-button {
  width: 100%;
}

:deep(.el-tabs__header) {
  margin-bottom: 25px;
}

:deep(.el-tabs__nav) {
  width: 100%;
  display: flex;
}

:deep(.el-tabs__item) {
  flex: 1;
  text-align: center;
}

:deep(.el-card__header) {
  padding: 20px 20px 0;
}

:deep(.el-form) {
  padding: 20px;
}

.captcha-container {
  display: flex;
  gap: 12px;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  height: 40px;
  cursor: pointer;
}

.math-captcha {
  min-height: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  color: #67c23a;
  font-size: 18px;
  font-weight: bold;
  padding: 8px 15px;
  cursor: pointer;
  user-select: none;
  transition: background-color 0.3s;
}

.math-captcha:hover {
  background-color: #e1f3d8;
}

.captcha-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.math-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}
</style> 